<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin\Api;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class ApiController extends Controller
{
    public function index(Request $request)
    {
        global $_G;
        if($request->isMethod('post')){
            $post = $request->input('delete');
            Api::destroy($post);
            return redirect()->route('admin.api')->with('status', 'success');
        }else {
            $res = ['title' => '我的'];
            //$res['user'] = Auth::user();
            $res['data'] = Api::orderby('created_at','desc')->Paginate($_G['perPage']);
            return view('admin.api.index', ['res' => $res]);
        }
    }

    public function add(Request $request)
    {
        if($request->isMethod('post')) {
            $api = new api;
            //$post = $api->check($request);
            $api->name = $request->input('name');
            $api->desc = $request->input('desc');
            $api->appkey = Str::random(128);
            $api->user_id = Auth::id();
            $api->url = $request->input('url');
            $api->ver = $request->input('ver');
            $api->status = $request->input('status');
            if($api->save()){
                return redirect()->route('admin.api')->with('status', 'success');
            }else{
                return back()->with('status', 'fail');
            }
        }else{
            $res=['title'=>'我的'];
            //$res['user']=Auth::user();
            return view('admin.api.add',['res'=>$res]);
        }

    }

    public function edit(Request $request)
    {
        if($request->isMethod('post')) {
            $api = Api::find($request->id);
            if($api){
                $api->name = $request->input('name');
                $api->desc = $request->input('desc');
                $api->appkey = $request->input('appkey');
                $api->url = $request->input('url');
                $api->ver = $request->input('ver');
                $api->status = $request->input('status');
                if($api->save()){
                    return redirect()->route('admin.api')->with('status', 'success');
                }
            }
            return back()->with('status', 'fail');
        }else{
            $res=['title'=>'我的'];
            //$res['user']=Auth::user();
            $res['info'] = Api::find($request->id);
            return view('admin.api.edit',['res'=>$res]);
        }
    }

    public function del(Request $request)
    {
        $api = Api::find($request->id);
        if($api){
            $api->delete();
        }
        return redirect()->route('admin.api')->with('status', 'success');
    }
}
